package com.spring.test;

import com.spring.model.Account;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.naming.spi.DirStateFactory;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration({"classpath:application.xml"})
public class Demo {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Test
    public void bean(){
        System.out.println(jdbcTemplate);
    }
    @Test
    public void insert(){
        String sql = "insert into account(uid, money) values(?, ?)";
        int update1 = jdbcTemplate.update(sql, 1, 9657);
        Assert.assertEquals(1, update1);
    }
    @Test
    public void findById() {
        String sql = "select * from account where id=?";
//        Map<String, Object> result = jdbcTemplate.queryForMap(sql, 7);
//        Set<String> keys=result.keySet();
//        for (String key:keys) {
//            System.out.println(key+":"+result.get(key));
//        }
        Account account=jdbcTemplate.queryForObject(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                Account account = new Account();
                account.setId(rs.getInt("id"));
                account.setUid(rs.getInt("uid"));
                account.setMoney(rs.getDouble("money"));
                return account;
            }
        }, 8);
        System.out.println(account);
    }
    @Test
    public void findAll() {
        String sql = "select * from account";
        List<Account> query = jdbcTemplate.query(sql, (rs, rowNum) -> {
            Account account = new Account();
            account.setId(rs.getInt("id"));
            account.setUid(rs.getInt("uid"));
            account.setMoney(rs.getDouble("money"));
            return account;
        });
        for (Account account : query) {
            System.out.println(account);
        }
    }
    }



